package com.nd.qa.shareplate.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.nd.qa.shareplate.common.CPResultCode;
import com.nd.qa.shareplate.common.SessionUserInfo;
import com.nd.qa.shareplate.common.SysConstant;
import com.nd.qa.shareplate.model.ElementAction;
import com.nd.qa.shareplate.model.ElementType;
import com.nd.qa.shareplate.model.Module;
import com.nd.qa.shareplate.model.PageElement;
import com.nd.qa.shareplate.model.SharePage;
import com.nd.qa.shareplate.service.ElementActionService;
import com.nd.qa.shareplate.service.ElementTypeService;
import com.nd.qa.shareplate.service.ModuleService;
import com.nd.qa.shareplate.service.PageElementService;
import com.nd.qa.shareplate.service.PageService;
import com.nd.qa.shareplate.util.FormatTimeUtil;
import com.nd.qa.shareplate.util.JsonUtil;


/**
 * <p>脚本模块控制类</p>
 * @author huangjian
 * @createDate 2015-09-12 下午 16:36:21
 * @version V1.0
 */
@Controller
@RequestMapping("/module/*")
public class ModuleController {

	private static Logger logger = LoggerFactory.getLogger(ModuleController.class);
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.ModuleService")
	private ModuleService moduleService;
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.PageService")
	private PageService pageService;
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.PageElementService")
	private PageElementService elementService;
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.ElementActionService")
	private ElementActionService actionService;
	
	@Autowired
	@Qualifier("com.nd.qa.shareplate.service.ElementTypeService")
	private ElementTypeService elementTypeService;
	
	/**
	 * 查检模块名称是否重复
	 * @param request
	 * @param response
	 * @param params
	 * @param session
	 */
	@RequestMapping("/checkModuleName")
	public void checkModuleName(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,HttpSession session){
		
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		Integer projectId = Integer.valueOf(String.valueOf(inParam.get("projectId")));
		String moduleName = String.valueOf(inParam.get("moduleName"));
		Module module = new Module();
		module.setProjectId(projectId);
		module.setModuleName(moduleName);
		try {
			Module module2 = moduleService.queryModuleByParams(module);
			if (module2!=null) {
				resultMap.put("code","-1");
				resultMap.put("data", "模块名称相同");
			}
			response.setCharacterEncoding("UTF-8");
		    response.setContentType("text/html;charset=UTF-8");
		    response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			logger.error("查询模块名称异常："+e.toString());
			e.printStackTrace();
		}
	}
	/**
	 * 添加模块信息
	 * @param request
	 * @param response
	 * @param params
	 * @param session
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/queryModuleById")
	public void queryModuleById(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,HttpSession session){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		if (sessionUserInfo==null) {
			//返回首页
			resultMap.put("code", "-1");
			resultMap.put("data", "您还未登录");
		}
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		Integer projectId = Integer.valueOf(String.valueOf(inParam.get("projectId")));
		String moduleId = String.valueOf(inParam.get("moduleId"));
		Module module = new Module();
		module.setProjectId(projectId);
		module.setModuleId(Integer.valueOf(moduleId));
		module.setOperatorId(sessionUserInfo.getUserId());
		try {
			Module module2 = moduleService.queryModuleByParams(module);
			resultMap.put("code", "0");
			resultMap.put("module", module2);
			response.setCharacterEncoding("UTF-8");
		    response.setContentType("text/html;charset=UTF-8");
		    response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			logger.error("查询模块异常："+e.toString());
			e.printStackTrace();
		}
	}
	/**
	 * 添加模块信息
	 * @param request
	 * @param response
	 * @param params
	 * @param session
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/insertModule")
	public void insertModule(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,HttpSession session){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		if (sessionUserInfo==null) {
			//返回首页
			resultMap.put("code", "-1");
			resultMap.put("data", "您还未登录");
		}
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		Integer projectId = Integer.valueOf(String.valueOf(inParam.get("projectId")));
		String moduleName = String.valueOf(inParam.get("moduleName"));
		String moduleLoginUrl = String.valueOf(inParam.get("moduleLoginUrl"));
		String moduleOrder = String.valueOf(inParam.get("moduleOrder"));
		Module module = new Module();
		module.setProjectId(projectId);
		module.setModuleName(moduleName);
		module.setModuleOrder(moduleOrder);
		module.setOperatorId(sessionUserInfo.getUserId());
		module.setModuleLoginUrl(moduleLoginUrl);
		module.setCreateTime(FormatTimeUtil.dateToStrLong(new Date()));
		try {
			HashMap<String, Object> returnMap = moduleService.insertModule(module);
			String code = (String) returnMap.get("code");
			if(CPResultCode.CP0000.equals(code)){
				resultMap.put("code", "0");
			}else {
				resultMap.put("code", "-1");
				resultMap.put("data", "添加模块失败");
			}
			response.setCharacterEncoding("UTF-8");
		    response.setContentType("text/html;charset=UTF-8");
		    response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			logger.error("添加项目模块异常："+e.toString());
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 自动构建可视化脚本
	 * @param request
	 * @param response
	 * @param params
	 * @param session
	 */
	@RequestMapping("buildModule")
	public void BuildModule(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,HttpSession session){
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		if (sessionUserInfo==null) {
			//返回首页
			resultMap.put("code", "-1");
			resultMap.put("data", "您还未登录");
		}
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		Integer projectId = Integer.valueOf(String.valueOf(inParam.get("projectId")));
		//发送apk请求
		
		//接收xml文件信息
		
		//解析xml文件信息
		File file = new File("E:\\baiduyun\\enumAppData.xml");
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(file);
			System.out.println("Root element :" 
		            + document.getRootElement().getName());
			Element classElement = document.getRootElement();
			//获取model节点，即根节点
			String modelName = classElement.attributeValue("name");
			String version = classElement.attributeValue("version");
			Module module = new Module();
			module.setProjectId(projectId);
			module.setModuleName(modelName);
			//创建模块信息
			moduleService.insertModule(module);
			Integer moduleId = module.getModuleId();//获取模块id
			//获取page首节点
			Element pageElement = classElement.element("page");
			String pageName = pageElement.attributeValue("name");
			Integer pageDepth = Integer.valueOf(pageElement.attributeValue("depth"));
			//创建模块下的第一个页面
			Integer rootPageId = pageService.queryPageSeqByName("page_seq");//根页面id
			SharePage rootPage = new SharePage();
			rootPage.setPageId(rootPageId);
			rootPage.setCreateTime(FormatTimeUtil.dateToStrLong(new Date()));
			rootPage.setModuleId(moduleId);
			rootPage.setElementTargetId(0);//新增子页面中的目标元素ID
			rootPage.setPageDepth(pageDepth);
			rootPage.setPageName(pageName);
			rootPage.setPageStatus(0);//0 普通页面 ；1 最后一页
			rootPage.setParentPageId(0);//无父页面
			rootPage.setStatus("A");
			pageService.insertPageInfo(rootPage);
			List<Element> elementLists = pageElement.elements("element");
			for (Element element : elementLists) {
				String elementType = element.attributeValue("elementType");
	            String text = element.attributeValue("text");
	            String id = element.attributeValue("id");
	            String match = element.attributeValue("match");
	            String actionType = element.attributeValue("actionType");
	            String elementName = element.attributeValue("elementName");
	            String dragCount = element.attributeValue("dragCount");
	            String elementText = element.attributeValue("text");
	            //查询元素列表序列
				Integer elementId = elementService.quertElmSeqByName("element_seq");
				PageElement pElement = new PageElement();
				pElement.setElementId(elementId);
				
				  //查询元素列表序列
				pElement.setElementName(elementName);
	            pElement.setCreateTime(FormatTimeUtil.dateToStrLong(new Date()));
	            if (dragCount!=null&&!"".equals(dragCount)) {
	            	 pElement.setDragCount(Integer.valueOf(dragCount));
				}
	            //通过elementActionName查询对应的id
	            ElementAction elementAction = actionService.queryElementActionInfo(actionType);
	            pElement.setElementActionName(actionType);
	            pElement.setElementActionId(elementAction.getElementActionId());
	            //通过elementType查询，elementTypeId信息
	            //ElementType eType = elementTypeService.queryElementTypeInfo(elementType);
	            pElement.setElementTypeFlag(0);
	            pElement.setElementTypeId(15);
	            if (id!=null&&!"".equals(id)&&!"null".equals(id)) {
	            	pElement.setElementTypeName("Id");
				}else{
					pElement.setElementTypeName(elementType);
				}
	            //通过id方式来查询组件
	            if (id!=null&&!"".equals(id)&&!"null".equals(id)) {
	            	 pElement.setElementContent(id);
				}else{
					pElement.setElementText(elementText);
				}
	            pElement.setElementOperationOrder(Integer.valueOf(match));
	            pElement.setElementOrder(Integer.valueOf(match));
	            pElement.setElementPreciousId(0);//TODO 暂时默认为0，即无前置元素
	            pElement.setElementText(text);
	            pElement.setPageId(rootPageId);
	            pElement.setStatus("A");
	            if (pElement!=null&&!"".equals(pElement)&&pElement.getPageId()!=null) {
					elementService.insertElememt(pElement);
				}
	            List<Element> childElements = element.elements("page");
	            if (childElements.size()!=0) {
					//从新的page开始
	            	for (Element childElement : childElements) {
						getPageAndElementInfo(childElement,rootPageId,moduleId,elementId);//elementId为子页面的目标元素id
					}
				}
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	/**
	 * 遍历XML信息
	 * @param childElement 页面子元素
	 * @param parentPageId	页面父Id
	 * @param moduleId	模块Id
	 * @param elementTargetId	子页面目标元素Id
	 */
	public void getPageAndElementInfo(Element childElement,Integer parentPageId,Integer moduleId,Integer elementTargetId){
		
		try {
			String pageName = childElement.attributeValue("name");
			Integer pageDepth = Integer.valueOf(childElement.attributeValue("depth"));
			Integer pageId = pageService.queryPageSeqByName("page_seq");//根页面id
			SharePage childPage = new SharePage();
			childPage.setPageId(pageId);
			childPage.setCreateTime(FormatTimeUtil.dateToStrLong(new Date()));
			childPage.setModuleId(moduleId);
			childPage.setElementTargetId(elementTargetId);//新增子页面中的目标元素ID
			childPage.setPageDepth(pageDepth);
			childPage.setPageName(pageName);
			childPage.setPageStatus(0);//0 普通页面 ；1 最后一页
			childPage.setParentPageId(parentPageId);//无父页面
			childPage.setStatus("A");
			pageService.insertPageInfo(childPage);
			List<Element> elements = childElement.elements("element");
			for (Element element : elements) {
				String elementType = element.attributeValue("elementType");
	            String text = element.attributeValue("text");
	            String id = element.attributeValue("id");
	            String match = element.attributeValue("match");
	            String actionType = element.attributeValue("actionType");
	            String elementName = element.attributeValue("elementName");
	            String dragCount = element.attributeValue("dragCount");
	            String elementText = element.attributeValue("text");
	            //查询元素列表序列
				Integer elementId = elementService.quertElmSeqByName("element_seq");
				PageElement pElement = new PageElement();
				pElement.setElementId(elementId);
				pElement.setElementName(elementName);
	            pElement.setCreateTime(FormatTimeUtil.dateToStrLong(new Date()));
	            if (dragCount!=null&&!"".equals(dragCount)) {
	            	 pElement.setDragCount(Integer.valueOf(dragCount));
				}
	            //通过elementActionName查询对应的id
	            ElementAction elementAction = actionService.queryElementActionInfo(actionType);
	            pElement.setElementActionName(actionType);
	            pElement.setElementActionId(elementAction.getElementActionId());
	            //通过elementType查询，elementTypeId信息
	            //ElementType eType = elementTypeService.queryElementTypeInfo(elementType);
	            pElement.setElementTypeFlag(0);
	            pElement.setElementTypeId(15);
	            if (id!=null&&!"".equals(id)&&!"null".equals(id)) {
	            	pElement.setElementTypeName("Id");
				}else{
					pElement.setElementTypeName(elementType);
				}
	            //通过id方式来查询组件
	            if (id!=null&&!"".equals(id)&&!"null".equals(id)) {
	            	 pElement.setElementContent(id);
				}else{
					pElement.setElementContent(elementText);
				}
	            pElement.setElementOperationOrder(Integer.valueOf(match));
	            pElement.setElementOrder(Integer.valueOf(match));
	            pElement.setElementPreciousId(0);//TODO 暂时默认为0，即无前置元素
	            pElement.setElementText(text);
	           
	            pElement.setPageId(pageId);
	            pElement.setStatus("A");
	            if (pElement!=null&&!"".equals(pElement)&&pElement.getPageId()!=null) {
					elementService.insertElememt(pElement);
				}
	            List<Element> childElements = element.elements("page");
	            for (Element childElement2 : childElements) {
					getPageAndElementInfo(childElement2, pageId, moduleId,elementId);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 修改项目根节点名称
	 * @param request
	 * @param response
	 * @param params
	 * @param session
	 */
	@RequestMapping("/updateModuleById")
	@SuppressWarnings("unchecked")
	public void updateModuleById(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,HttpSession session){
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		
		try {
			HashMap<String, Object> resultMap = new HashMap<String,Object>();
			if (sessionUserInfo==null) {
				//返回首页
				resultMap.put("code", "-1");
				resultMap.put("data", "您还未登录");
				response.getWriter().print(JsonUtil.toString(resultMap));
			}
			HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
			Integer projectId = Integer.valueOf(String.valueOf(inParam.get("projectId")));
			Integer moduleId = Integer.valueOf(String.valueOf(inParam.get("moduleId")));
			String moduleName = String.valueOf(inParam.get("moduleName"));
			String modifyModuleUrl = String.valueOf(inParam.get("modifyModuleUrl"));
			String modifyModuleOrder = String.valueOf(inParam.get("modifyModuleOrder"));
			Module module = new Module();
			module.setProjectId(projectId);
			module.setModuleId(moduleId);
			module.setModuleName(moduleName);
			module.setModuleOrder(modifyModuleOrder);
			module.setModuleLoginUrl(modifyModuleUrl);
			module.setOperatorId(sessionUserInfo.getUserId());
			module.setUpdateTime(FormatTimeUtil.dateToStrLong(new Date()));
			HashMap<String, Object> returnMap = moduleService.updateModuleById(module);
			String code = (String) returnMap.get("code");
			if(CPResultCode.CP0000.equals(code)){
				resultMap.put("code", "0");
			}else {
				resultMap.put("code", "-1");
				resultMap.put("data", "添加模块失败");
			}
			response.setCharacterEncoding("UTF-8");
		    response.setContentType("text/html;charset=UTF-8");
		    response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			logger.error("添加项目模块异常："+e.toString());
			e.printStackTrace();
		}
		
	}
	/**
	 * 删除模块信息
	 * @param request
	 * @param response
	 * @param params
	 * @param session
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/deleteModuleById")
	public void deleteModuleById(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,HttpSession session){
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		try {
			HashMap<String, Object> resultMap = new HashMap<String,Object>();
			if (sessionUserInfo==null) {
				//返回首页
				resultMap.put("code", "-1");
				resultMap.put("data", "您还未登录");
				response.getWriter().print(JsonUtil.toString(resultMap));
			}
			HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
			Integer projectId = Integer.valueOf(String.valueOf(inParam.get("projectId")));
			Integer moduleId = Integer.valueOf(String.valueOf(inParam.get("moduleId")));
			Module module = new Module();
			module.setProjectId(projectId);
			module.setModuleId(moduleId);
			module.setOperatorId(sessionUserInfo.getUserId());
			module.setUpdateTime(FormatTimeUtil.dateToStrLong(new Date()));
			HashMap<String, Object> returnMap = moduleService.deleteModuleById(module);
			String code = (String) returnMap.get("code");
			if(CPResultCode.CP0000.equals(code)){
				resultMap.put("code", "0");
			}else {
				resultMap.put("code", "-1");
				resultMap.put("data", "添加模块失败");
			}
			response.setCharacterEncoding("UTF-8");
		    response.setContentType("text/html;charset=UTF-8");
		    response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			logger.error("添加项目模块异常："+e.toString());
			e.printStackTrace();
		}
	}
	/**
	 * 展示界面右边的脚本结构图
	 * @param request
	 * @param response
	 * @param params
	 * @param session
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/showScriptChart")
	public void showScriptChart(HttpServletRequest request,HttpServletResponse response,@RequestBody String params,HttpSession session){
		
		SessionUserInfo sessionUserInfo = (SessionUserInfo) session.getAttribute(SysConstant.SESSION_KEY_LOGIN_USER);
		HashMap<String, Object> resultMap = new HashMap<String,Object>();
		HashMap<String, Object> defaultPage = new HashMap<String,Object>();
		if (sessionUserInfo==null) {
			//返回首页
			resultMap.put("code", "-1");
			resultMap.put("data", "您还未登录");
		}
		HashMap<String, Object> inParam = JsonUtil.toObject(params, HashMap.class);
		Integer moduleId = Integer.valueOf(String.valueOf(inParam.get("moduleId")));
		Integer projectId = Integer.valueOf(String.valueOf(inParam.get("projectId")));
		try {
			//查询是否已存在page信息
			List<HashMap<String, Object>> pageList = pageService.queryPageList(moduleId);
			//查询跟模块的信息
			Module module = new Module();
			module.setProjectId(projectId);
			module.setModuleId(moduleId);
			List<HashMap<String, Object>> rootModuleList = moduleService.getProjectModule(module);
			for (int i = 0; i < rootModuleList.size(); i++) {
				HashMap<String, Object> rootModule = rootModuleList.get(i);
				defaultPage.put("depth", 0);
				defaultPage.put("page_status", 0);
				defaultPage.put("page_id", 0);
				defaultPage.put("page_name", rootModule.get("module_name"));
				defaultPage.put("parent_page_id", -1);
				defaultPage.put("module_id", moduleId);
				defaultPage.put("module_name", rootModule.get("module_name"));
				resultMap.put("defaultPage", defaultPage);
			}
			if (pageList.size()>0) {
				pageList.add(defaultPage);
			}
			resultMap.put("pageList", pageList);
			resultMap.put("code", "0");
			response.setCharacterEncoding("UTF-8");
		    response.setContentType("text/html;charset=UTF-8");
		    response.getWriter().print(JsonUtil.toString(resultMap));
		} catch (Exception e) {
			logger.error("查询page异常："+e.toString());
			e.printStackTrace();
		}
	}
}
